package com.mapbased.sfw.model;

import java.util.Map;

import org.dom4j.Element;

import com.mapbased.sfw.component.Component;
import com.mapbased.sfw.component.Headable;
import com.mapbased.sfw.component.XmlContext;
import com.mapbased.sfw.component.Xmlable;

/**
 * a Fragment can be :Fragment,page,or masterpage
 * 
 * @author Administrator
 * 
 */
public class Fragment implements Xmlable {

	protected String path;
	

	protected long loadTime = System.currentTimeMillis();
	protected long pageLMD;

	protected RenderGroup mainRenderGroup;

	Map<String, Component> components;
	Headable[] headables;
	
	public long lastModified(RenderContext rc){
		return -1L;
	}
	public String getPath() {
		return path;
	}

	public void handleAction(RenderContext rc) {

		String componenthandler = rc.req.param("ch");

		if (componenthandler == null) {
			return;
		}

	}

	public void prepareHeadables(RenderContext rc) {
		if (this.headables != null) {
			for (Headable h : this.headables) {
				h.doHead(rc);
			}
		}
	}

	public void render(RenderContext rc) {
		rc.setCurrentFragment(this);

		mainRenderGroup.render(rc);
	}

	@Override
	public String getTypeName() {
		// TODO Auto-generated method stub
		return "Fragment";
	}

	@Override
	public void parseXml(Element ele, LoadContext lc) {
		Element n = (Element) ele.selectSingleNode("//*[@jid=\"$content$\"]");
		// System.out.println(doc.getDocType().asXML());
		if (n != null) {
			lc.parseElementChildren(n);
		} else {

			lc.parseElement(ele);
		}
		this.mainRenderGroup = lc.getRenderGroup();
		// @need synchronized map?
		this.components = lc.components;
		this.headables = lc.headables
				.toArray(new Headable[lc.headables.size()]);

	}

	@Override
	public void toXml(XmlContext xc) {
		StringBuilder sb = xc.sb;
		sb.append("<div jid=\"$content$\" >");
		this.mainRenderGroup.toXml(xc);
		sb.append("</div>");

	}

}
